package com.swift.utils;


import java.io.IOException;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.widget.Toast;


public class NfcHelper {
	public static final int UNSUPPORT = 1;
	public static final int UNSETUP = 2;
	
	private NfcAdapter mNfcAdapter; 
	private Activity mActivity;
	private PendingIntent mPendingIntent;
	private IntentFilter[] mIntentFilters;
	private String[][] mTechs;
	
	public NfcHelper(Activity activity, NfcAdapter nfcAdapter) {
		mActivity = activity;
		mNfcAdapter = nfcAdapter;		
		setForegroundDispatchFilter();
	}
	
	
	private void setForegroundDispatchFilter(){
		mPendingIntent = PendingIntent.getActivity(mActivity, 0, new Intent(mActivity, mActivity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
		try {
			intentFilter.addDataType("*/*");
		} catch (MalformedMimeTypeException e) {
			throw new RuntimeException("fail", e);
		}
		mIntentFilters = new IntentFilter[] { intentFilter, };
		mTechs= new String[][] { new String[] { NfcA.class.getName() } };
	}
	
	public void enableForegroundDispatch() {
		if (mNfcAdapter != null){
			mNfcAdapter.enableForegroundDispatch(mActivity, mPendingIntent, mIntentFilters, mTechs);
		}
	}
	
	public void disableForegroundDispatch() {
		if (mNfcAdapter != null){
			mNfcAdapter.disableForegroundDispatch(mActivity);
		}
	}
	
	public String getTagUID(Intent intent){
		if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {       
			Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);  
			byte[] idArray = tagFromIntent.getId();
			return SysUtils.bytesToHexString(idArray);			
        }  
		return null;
	}
	
	
}
